// 测试页面控制器
class TestController {
    constructor() {
        this.pageMapping = {
            character: { path: '../character/index.html', name: '角色测试' },
            backpack: { path: '../backpack/index.html', name: '背包测试' },
            rank: { path: 'rank/index.html', name: '排行测试' },
            card: { path: 'card/index.html', name: '卡片测试' }
        };
        this.init();
    }

    init() {
        // 绑定按钮事件
        document.getElementById('btnCharacter')?.addEventListener('click', () => {
            this.openTestPage('character');
        });

        document.getElementById('btnBackpack')?.addEventListener('click', () => {
            this.openTestPage('backpack');
        });

        document.getElementById('btnRank')?.addEventListener('click', () => {
            this.openTestPage('rank');
        });

        document.getElementById('btnCard')?.addEventListener('click', () => {
            this.openTestPage('card');
        });

        // 绑定弹窗确认按钮
        document.getElementById('modalConfirm')?.addEventListener('click', () => {
            this.hideModal();
        });

        // 点击弹窗背景关闭
        document.getElementById('modalOverlay')?.addEventListener('click', (e) => {
            if (e.target.id === 'modalOverlay') {
                this.hideModal();
            }
        });

        // ESC键关闭弹窗
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.hideModal();
            }
        });

        console.log('测试页面控制器初始化完成');
    }

    /**
     * 打开测试页面
     * @param {string} pageType 页面类型 (character/backpack/rank/card)
     */
    async openTestPage(pageType) {
        const pageInfo = this.pageMapping[pageType];
        if (!pageInfo) {
            this.showModal('未知的测试页面类型');
            return;
        }

        const pagePath = pageInfo.path;
        const fullPath = pagePath; // 相对于当前页面的路径

        // 检查页面是否存在
        const exists = await this.checkPageExists(fullPath);
        
        if (!exists) {
            this.showModal(`页面不存在: ${pagePath}\n请先创建对应的测试页面文件`);
            return;
        }

        // 获取测试数据
        const testData = this.getTestData();
        
        // 传递数据并打开页面
        this.passDataAndOpen(pagePath, testData);
    }

    /**
     * 检查页面是否存在
     * @param {string} path 页面路径
     * @returns {Promise<boolean>}
     */
    async checkPageExists(path) {
        // 本地 file:// 环境下，无法通过 fetch 检测，直接放行
        if (location.protocol === 'file:') {
            return true;
        }

        try {
            const response = await fetch(path, { method: 'HEAD' });
            return response.ok;
        } catch (error) {
            // 如果HEAD请求失败，尝试GET请求
            try {
                const response = await fetch(path, { method: 'GET' });
                return response.ok && response.headers.get('content-type')?.includes('text/html');
            } catch (e) {
                // 网络或跨域等异常时，允许退化为直接打开，由浏览器处理
                return true;
            }
        }
    }

    /**
     * 获取测试数据
     * @returns {object|null}
     */
    getTestData() {
        const dataInput = document.getElementById('testData');
        const dataText = dataInput?.value.trim() || '';
        
        if (!dataText) {
            return null;
        }

        try {
            return JSON.parse(dataText);
        } catch (error) {
            console.warn('测试数据格式错误，将使用空数据:', error);
            this.showModal('测试数据格式错误，将使用空数据打开页面');
            return null;
        }
    }

    /**
     * 传递数据并打开页面
     * @param {string} pagePath 页面路径
     * @param {object|null} data 测试数据
     */
    passDataAndOpen(pagePath, data) {
        // 针对不同页面类型使用不同数据键
        const isCharacter = pagePath.includes('/character/');

        if (isCharacter) {
            if (data) {
                localStorage.setItem('characterData', JSON.stringify(data));
                localStorage.setItem('characterDataTimestamp', Date.now().toString());
            } else {
                localStorage.removeItem('characterData');
                localStorage.removeItem('characterDataTimestamp');
            }
        } else {
            if (data) {
                localStorage.setItem('testData', JSON.stringify(data));
                localStorage.setItem('testDataTimestamp', Date.now().toString());
            } else {
                localStorage.removeItem('testData');
                localStorage.removeItem('testDataTimestamp');
            }
        }

        // URL参数备用
        let url = pagePath;
        if (data) {
            try {
                const params = new URLSearchParams();
                params.set(isCharacter ? 'characterData' : 'testData', JSON.stringify(data));
                url = pagePath + '?' + params.toString();
            } catch (error) {
                console.warn('URL参数传递失败，仅使用localStorage:', error);
            }
        }

        const win = window.open(url, '_blank');
        // 如果被拦截或失败，回退到当前窗口打开
        if (!win) {
            window.location.href = url;
        }
    }

    /**
     * 显示弹窗
     * @param {string} message 提示消息
     */
    showModal(message) {
        const overlay = document.getElementById('modalOverlay');
        const messageEl = document.getElementById('modalMessage');
        
        if (overlay && messageEl) {
            messageEl.textContent = message;
            overlay.classList.add('show');
        }
    }

    /**
     * 隐藏弹窗
     */
    hideModal() {
        const overlay = document.getElementById('modalOverlay');
        if (overlay) {
            overlay.classList.remove('show');
        }
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new TestController();
});

